'use strict';
const xlsx = require('xlsx');
const fs = require('fs');

const { Controller } = require('egg');
const { Op } = require('sequelize');
const { uploadExcel } = require('../extend/helper');
const serviceName = 'energyTimeData'
function  formatDate(numb, format) {
  const time = new Date((numb - 1) * 24 * 3600000 + 1)
  time.setYear(time.getFullYear() - 70)
  const year = time.getFullYear() + ''
  const month = time.getMonth() + 1 + ''
  const date = time.getDate() - 1 + ''
  const hour = time.getHours()
  const minute = time.getMinutes()
    const second = time.getSeconds()
  console.log(hour, minute, second)
  if (format && format.length === 1) {
    return year + format + month + format + date
  }
  return year + (month < 10 ? '0' + month : month) + (date < 10 ? '0' + date : date)  + `${hour}:${minute}:${second}`
}
class RouterController extends Controller {
  /**
   * 上传的时excel文件，每行数据对应数据库的一条记录
   */
  async upload() {
    let file;
    try {
      file = this.ctx.request.files[0];
      const list = new Array(0);
      const workbook = xlsx.readFile(file.filepath);
      for (const sheet in workbook.Sheets) {
        if (workbook.Sheets.hasOwnProperty(sheet)) {
          // 数据直接转成json格式
          list.push(xlsx.utils.sheet_to_json(workbook.Sheets[sheet]));
        }
      }
        const templist = list[0].map(item => {
          console.log(formatDate(item['时间'], '-'))
          return {
              name: formatDate(item['时间'], '-'),
              value: item['值'],
            }
        })
        await this.ctx.service[serviceName].upload(templist);
        this.ctx.success();
    } catch (error) {

    }
  }

  // 分页
  async index() {
    const { query, service } = this.ctx;
    let { pageNum, pageSize, start_time= '', end_time='' } = query;
    let page = Number(pageNum) || 1;
    let size = Number(pageSize) || 10;
    const where = {

    };
    if (start_time && end_time) {
        where.name = {
            [Op.gte]: start_time,
            [Op.lte]: end_time
        }
    }
    const list = await service[serviceName].getPage(where, page, size);
    this.ctx.success(list);
  }
  // 新增
  async create() {
    const { ctx } = this;
    const data = ctx.request.body;
    await ctx.service[serviceName].create(data);
    ctx.success(data, 200);
  }
  // 修改
  async update() {
    const { ctx } = this;
    const id = ctx.params.id;
    const infos = ctx.request.body;
    if (!id) throw new Error('必须传递ID参数');
    if (Object.keys(infos).length === 0) throw new Error('请传递修改的内容');
    await ctx.service[serviceName].update(id, infos);
    ctx.success(id, 200);
  }
  // 删除
  async destroy() {
    const uid = Number(this.ctx.params.id);
    if (!uid) throw new Error('ID 有误');
    await this.ctx.service[serviceName].deleteById(uid);
    this.ctx.success(uid); // 删除成功返回被删除的用户ID
  }
  // 查看
  async show() {
    const { params, service } = this.ctx;
    const findItem = await service[serviceName].findOne(params.id);
    this.ctx.success(findItem);
  }
  // 所有列表
  async allList() {
    const { service , query} = this.ctx;
    let { start_time, end_time } = query;
    let where = {}
    if (start_time && end_time) {
      where.name = {
        [Op.gte]: start_time,
        [Op.lte]: end_time
      }
    }
    const list = await service[serviceName].allList(where);
    this.ctx.success(list);
  }
}

module.exports = RouterController;
